package no.nordicsemi.android.nrfmesh.auth.data;

import android.content.Context;

import no.nordicsemi.android.nrfmesh.auth.data.db.*;
import no.nordicsemi.android.nrfmesh.auth.util.Passwords;

/** 纯本地认证仓库：注册、登录、资料保存 */
public class AuthRepository {
    private final AccountDao accDao;
    private final UserProfileDao userDao;
    private final DoctorProfileDao docDao;

    public AuthRepository(Context c) {
        AuthDatabase db = AuthDatabase.get(c);
        this.accDao = db.accountDao();
        this.userDao = db.userProfileDao();
        this.docDao = db.doctorProfileDao();
    }

    public static final String ROLE_USER = "USER";
    public static final String ROLE_DOCTOR = "DOCTOR";

    private void ensureIdUnique(String username) {
        if (accDao.byUsername(username) != null) {
            throw new IllegalStateException("该 ID 已存在");
        }
    }

    private Account makeAccount(String username, char[] pd, String role) throws Exception {
        Account a = new Account();
        a.username = username;
        a.role = role;
        a.salt = Passwords.salt();
        a.passHash = Passwords.hash(pd, a.salt);
        a.createdAt = System.currentTimeMillis();
        return a;
    }

    /** 注册：普通用户 */
    public long registerUser(String id, char[] pd, String name, String gender, Integer age) throws Exception {
        ensureIdUnique(id);
        Account a = makeAccount(id, pd, ROLE_USER);
        long aid = accDao.insert(a);

        UserProfile up = new UserProfile();
        up.accountId = aid; up.name = name; up.gender = gender; up.age = age;
        userDao.insert(up);
        return aid;
    }

    /** 注册：医生 */
    public long registerDoctor(String id, char[] pd, String name, String hospital) throws Exception {
        ensureIdUnique(id);
        Account a = makeAccount(id, pd, ROLE_DOCTOR);
        long aid = accDao.insert(a);

        DoctorProfile dp = new DoctorProfile();
        dp.accountId = aid; dp.name = name; dp.hospital = hospital;
        docDao.insert(dp);
        return aid;
    }

    /** 登录：校验 id/pd 成功则返回 Account */
    public Account login(String id, char[] pd) throws Exception {
        Account a = accDao.byUsername(id);
        if (a == null) throw new IllegalStateException("ID 不存在");
        if (!Passwords.verify(pd, a.salt, a.passHash)) throw new IllegalStateException("PD 不正确");
        a.lastLoginAt = System.currentTimeMillis();
        accDao.update(a);
        return a;
    }

    public UserProfile userProfile(long accountId) { return userDao.byAccount(accountId); }
    public DoctorProfile doctorProfile(long accountId) { return docDao.byAccount(accountId); }
}
